package com.redare.dev.smart.generator.sdk.utils;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.log.NullLogChute;

import java.io.StringWriter;
import java.nio.charset.StandardCharsets;

/**
 */
public class VelocityUtil {

    protected final static VelocityEngine VELOCITY_ENGINE = new VelocityEngine();

    static {
        /*
          IDEA 的 URLClassLoader 无法获取当前插件的 path
          @see org.apache.velocity.util.ClassUtils
         */
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(VelocityUtil.class.getClassLoader());
        VELOCITY_ENGINE.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, NullLogChute.class.getName());
        VELOCITY_ENGINE.loadDirective("com.redare.dev.smart.generator.sdk.directive.LowerCase");
        VELOCITY_ENGINE.loadDirective("com.redare.dev.smart.generator.sdk.directive.AllLowerCase");
        VELOCITY_ENGINE.loadDirective("com.redare.dev.smart.generator.sdk.directive.UpperCase");
        VELOCITY_ENGINE.loadDirective("com.redare.dev.smart.generator.sdk.directive.Append");
        VELOCITY_ENGINE.loadDirective("com.redare.dev.smart.generator.sdk.directive.Split");
        VELOCITY_ENGINE.loadDirective("com.redare.dev.smart.generator.sdk.directive.ImportPackage");
        VELOCITY_ENGINE.loadDirective("com.redare.dev.smart.generator.sdk.directive.GetPackage");
        VELOCITY_ENGINE.loadDirective("com.redare.dev.smart.generator.sdk.directive.ReplacePoint");
        Thread.currentThread().setContextClassLoader(classLoader);
    }

    public static String evaluate(Context context, String inputStr)  {
        StringWriter writer = new StringWriter();
        VELOCITY_ENGINE.evaluate(context, writer, "", new String(inputStr.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
        return writer.toString();
    }

}
